package com.weishenai.customerassistant.utils;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;

/**
 * 微信工具类
 */
@Slf4j
@Component
public class WeChatUtil {
    // 微信小程序ID
    @Value("${weixin.appid}")
    private String APPID;
    // 微信小程序秘钥
    @Value("${weixin.appSecret}")
    private String APPSECRET;

    /**
     * 微信向服务器发送请求
     *
     * @param requestUrl
     * @param requestMethod
     * @param output
     * @return
     */
    public String httpRequest(String requestUrl, String requestMethod, String output) {
        try {
            URL url = new URL(requestUrl);
            HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            if (null != output) {
                OutputStream outputStream = connection.getOutputStream();
                outputStream.write(output.getBytes("utf-8"));
                outputStream.close();
            }
            // 从输入流读取返回内容
            InputStream inputStream = connection.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            StringBuffer buffer = new StringBuffer();
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            inputStream = null;
            connection.disconnect();
            return buffer.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 根据微信的临时code换区用户的openid
     *
     * @param code 微信的临时code
     * @return openid
     */
    public String getOpenId(String code) {
        // 微信小程序ID
        String appid = APPID;
        // 微信小程序秘钥
        String secret = APPSECRET;
        // 根据小程序穿过来的code想这个url发送请求
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code";
        // 发送请求，返回Json字符串
        String str = httpRequest(url, "GET", null);
        // 转成Json对象 获取openid
        JSONObject jsonObject = JSONObject.parseObject(str);
        log.info("WeChatMessage：" + str);
        // 我们需要的openid，在一个小程序中，openid是唯一的
        if (jsonObject.get("openid") == null) return null;
        String openid = jsonObject.get("openid").toString();
        log.info("工具类获取的openID:" + openid);
        return openid;
    }
}
